import { createItem, deleteItem, getData, updateItem } from '.'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'

const useCrud = () => {
  const queryClient = useQueryClient()
  const useItems = (
    url: string,
    pageNum: number,
    pageSize: number,
    searchParams?: any
  ) =>
    useQuery({
      queryKey: [url, pageNum, pageSize, searchParams],
      queryFn: () => getData(url, pageNum, pageSize, searchParams)
    })
  const useCreateItem = (url: string) =>
    useMutation({
      mutationFn: (data: any) => createItem(url, data),
      onSuccess: () => queryClient.invalidateQueries([url])
    })
  const useUpdateItem = (url: string) =>
    useMutation({
      mutationFn: ({ id, data }: { id: string; data: any }) => {
        updateItem(url, id, data)
      },
      onSuccess: () => queryClient.invalidateQueries([url])
    })
  const useDeleteItem = (url: string) =>
    useMutation({
      mutationFn: (id: string) => deleteItem(url, id),
      onSuccess: () => queryClient.invalidateQueries([url])
    })
  return {
    useItems,
    useCreateItem,
    useUpdateItem,
    useDeleteItem
  }
}

export default useCrud
